<template>
    <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
            <el-form label-position="top" :model="editForm" :rules="editFormRules" ref="editForm" @submit.native.prevent>
                <input type="hidden"  v-model="editForm.id">
                <el-form-item label="点位名称：" prop="name">
                    <el-input v-model="editForm.name" auto-complete="off" placeholder="请输入点位名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="所在建筑物：" prop="fbsId">
                    <tree-select
                        v-model="editForm.fbsId"
                        filterable
                        :data="buildList"
                        :defaultProps="buildDefaultProps"
                        :checkedKeys="defaultCheckedFbsId"
                        :nodeKey="buildNodeKey">
                    </tree-select>
                </el-form-item>
                <el-form-item label="点位类别：" prop="pointTypeId">
                  <el-select filterable v-model="editForm.pointTypeId">
                    <el-option
                      v-for="item in pointTypeOptions"
                      :key="item.id"
                      :label="item.pointTypeName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="点位具体地址：">
                    <el-input v-model="editForm.address" auto-complete="off" clearable></el-input>
                </el-form-item>
                <el-form-item label="二维码编码：">
                    <el-input :disabled="editForm.id?true:false" v-model="editForm.visualCode" auto-complete="off" clearable placeholder="不填，则由系统自动生成"></el-input>
                </el-form-item>
                <el-form-item label="点位图片：">
                  <el-upload
                      :action="QINIUUPLOADURL"
                      :multiple="true"
                      ref="upload"
                      list-type="picture-card"
                      :data="qiniuData"
                      :on-success="handleAvatarSuccess"
                      :on-remove="handleRemovePic"
                      :on-error="handleError"
                      :before-upload="beforeAvatarUpload"
                      :on-preview="$imgPreview"
                      :file-list="qiniuData.fileList" 
                      accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                      <i class="el-icon-plus"></i>
                  </el-upload>
                </el-form-item>
                <el-form-item label-width="0" class="verifyidentity-button">
                    <el-button round @click="closeDialog()">取消</el-button>
                    <el-button type="primary" round @click="savePointType('editForm')">确定</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<script>
import util from '@/utils/util'
import { qnToken} from '@/api/api'
import { getFbsTree} from '@/api/fbs'
import * as Dao from '@/api/inspect'
import TreeSelect from '@/libs/TreeSelect/Main'

export default {
  name:'InspectPointForm',
  components: { 
    TreeSelect
  },
  props: {
    editInfo: {
        type: Object,
        required: false
    },
    closeDialog: {
        type: Function,
        required: true
    },/*
    buildList: {
        type: Array,
        required: true
    }*/
  },
  data() {
    return {
      buildList:[],
        qiniuData:{//上传图片携带的参数
            token : "",
            key : "",
            fileList:[],
        },
        defaultImg: this.GLOBAL.defaultImg,
        util:util,
        pointTypeOptions:[],
        // 建筑物
        buildDefaultProps: {
            children: 'nodes',
            label: 'text',
            value: 'id'
        },
        buildNodeKey: 'id',
        defaultCheckedFbsId: [],
        editForm: {
            id: '',
            orgId:this.$store.state.userinfo.org.id,
            address:'',
            name: '',
            picUrl:'',
            visualCode:'',
            pointTypeId:'',
            picUrl:'',
            fbsId:''
        },
        editFormRules: {
            fbsId: [
                { required: true, message: '请选择所在建筑物', trigger: 'blur' }
            ],
            name: [
                { required: true, message: '请输入点位类别名称', trigger: 'blur' },
            ],
            pointTypeId: [
                { required: true, message: '请选择点位类别', trigger: 'blur' },
            ],
        },
    }
  },
  created() {
      let infoObj = this.editInfo
      if(infoObj.id) {//编辑
          this.editForm.id = infoObj.id
          this.editForm.orgId = infoObj.orgId
          this.editForm.address = infoObj.address
          this.editForm.name = infoObj.name
          this.editForm.visualCode = infoObj.visualCode
          //this.defaultCheckedFbsId = infoObj.fbsId.toString().split(',')
          //this.editForm.fbsId = infoObj.fbsId
          this.editForm.pointTypeId = infoObj.pointTypeId
          this.editForm.picUrl = infoObj.picUrl
          infoObj.picUrl?$.each(infoObj.picUrl.split(','),(index,url)=>{
            this.qiniuData.fileList.push({
                name:'现场图片'+index,
                url:url
            })
          }):''
      }
      this.getData()
      this.getToken();//获取token
  },
  methods: {
    getData() {
      let that = this
      getFbsTree({
        organizationId: that.editForm.orgId
      }).then(res => {
        that.buildList = res.data.length === 0 ?[] : res.data
        /*
         * 多选建筑物结构树初始赋值问题
         */
        that.$nextTick(() => {
            if(that.editInfo.id) {//编辑 
              that.defaultCheckedFbsId = that.editInfo.fbsId.toString().split(',')
              that.editForm.fbsId = that.editInfo.fbsId
            }
        })
      })
      Dao.getInspectPointTypeList({
        queryType : 0,
        orgIds: that.editForm.orgId
      }).then((data)=>{
        that.pointTypeOptions.push.apply(this.pointTypeOptions,data.data);
      })
      
    },
    getToken(){  //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token= result.data
      })
    },
    beforeAvatarUpload: function(file){//重命名和校验
      var fielLocal = file.name.split(".")
      var fielType = "." + fielLocal[fielLocal.length-1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink_'+new Date().getTime()+fielType   
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isJPG && !isPNG) {
        this.$message.error("图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt20M) {
        this.$message.error("图片大小不能超过 20MB!");
        return false;
      }
    },
    handleAvatarSuccess: function(res, file, fileList) {//上传成功
      this.qiniuData.fileList = fileList;
    },
    handleRemovePic: function(file, fileList) {//删除成功
      this.qiniuData.fileList = fileList;
    },
    handleError: function(res) {
      this.$message({
        message: "上传失败",
        duration: 2000,
        type: "warning"
      });
    },
    savePointType(formName) {
        // 阻止事件冒泡
        event.stopPropagation()
        let that = this
        that.$refs[formName].validate((valid) => {
            if (valid) {
                let parames = that.editForm
                parames.picUrl = util.ilinkArrHandle.getqiniuPicUrlArr(this.qiniuData.fileList).toString()
                let upFn = parames.id?Dao.updateInspectPointNewById:Dao.addInspectPointNew
                upFn(parames).then(res => {
                    that.$message({
                        message: '保存成功！',
                        type: 'success'
                    })
                    that.closeDialog(true)
                });
            } else {
                return false
            }
        });
    },
  }
}
</script>